<template>
    <el-dialog v-model="visible" title="品牌合并" :close-on-click-modal="false" :close-on-press-escape="false" width="80%">
        <!-- 步骤一：筛选查询品牌数据 -->
        <div v-if="currentStep === 1">
            <div class="step-subtitle">请选择需要合并的品牌</div>

            <!-- 筛选条件 -->
            <el-form label-width="80px" :model="state.dataForm" ref="dataFormRef" @submit.prevent="query">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="品牌名称">
                            <el-input v-model="state.dataForm.brandName" placeholder="请输入品牌名称" @keyup.enter="query"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" :offset="1">
                        <el-button @click="query" type="primary">查询</el-button>
                    </el-col>
                </el-row>
            </el-form>

            <!-- 品牌列表 -->
            <el-table
                v-loading="state.dataListLoading"
                :data="state.dataList"
                border
                @selection-change="handleSelectionChange"
                style="width: 100%; margin-top: 20px;">
                <el-table-column type="selection" align="center" width="50"></el-table-column>
                <el-table-column align="center" prop="brandCode" label="品牌编号" width="150"></el-table-column>
                <el-table-column align="center" prop="brandName" label="品牌名称" width="150"></el-table-column>
                <el-table-column align="center" prop="brandClassifyName" label="产地" width="120"></el-table-column>
                <el-table-column align="center" prop="createAt" label="创建时间" width="180"></el-table-column>
                <el-table-column align="center" prop="createUsername" label="创建人"></el-table-column>
            </el-table>

            <!-- 底部按钮 -->
            <div class="dialog-footer">
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="goToStep2" :disabled="selectedBrands.length < 2">下一步</el-button>
            </div>
        </div>

        <!-- 步骤二：选择要保留的品牌 -->
        <div v-if="currentStep === 2">
            <div class="step-subtitle">请选择需要保留的品牌</div>

            <!-- 选中的品牌列表 -->
            <el-table
                :data="selectedBrands"
                border
                @selection-change="handleMainBrandSelection"
                style="width: 100%; margin-top: 20px;">
                <el-table-column type="selection" align="center" width="50"></el-table-column>
                <el-table-column align="center" prop="brandCode" label="品牌编号" width="150"></el-table-column>
                <el-table-column align="center" prop="brandName" label="品牌名称" width="150"></el-table-column>
                <el-table-column align="center" prop="brandClassifyName" label="产地" width="120"></el-table-column>
                <el-table-column align="center" prop="createAt" label="创建时间" width="180"></el-table-column>
                <el-table-column align="center" prop="createUsername" label="创建人"></el-table-column>
            </el-table>

            <!-- 底部按钮 -->
            <div class="dialog-footer">
                <el-button @click="goToStep1" :disabled="merging">上一步</el-button>
                <el-button
                    type="primary"
                    @click="handleMerge"
                    :disabled="!mainBrand || merging"
                    :loading="merging">
                    {{ merging ? '合并中...' : '完成' }}
                </el-button>
            </div>
        </div>
    </el-dialog>
</template>

<script lang="ts" setup>
import useView from "@/hooks/useView";
import { reactive, ref, toRefs } from "vue";
import baseService from "@/service/baseService";
import { ElMessage, ElMessageBox } from "element-plus";

// 定义视图配置
const view = reactive({
    getDataListURL: '/base/basebrand/listForMerge', // 品牌列表接口
    getDataListIsPage: false, // 不分页，获取所有数据
    notGetData: true,
    dataForm: {
        brandName: ""
    },
});

const dataFormRef = ref();
const visible = ref(false);
const emit = defineEmits(['click', 'refreshDataList']);

// 步骤控制
const currentStep = ref(1); // 当前步骤：1-选择品牌，2-选择保留品牌
const selectedBrands = ref<any[]>([]); // 第一步选中的品牌
const mainBrand = ref<any>(null); // 第二步选中的主品牌
const merging = ref(false); // 合并操作进行中状态

// 初始化
const init = () => {
    visible.value = true;
    currentStep.value = 1;
    selectedBrands.value = [];
    mainBrand.value = null;

    // 重置表单数据
    if (dataFormRef.value) {
        dataFormRef.value.resetFields();
    }

    // 清空数据列表
    state.dataList = [];
    state.notGetData = true;
};

const query = () => {
    state.notGetData = false;
    state.getDataList();
};

// 第一步：处理品牌选择
const handleSelectionChange = (selection: any[]) => {
    selectedBrands.value = selection;
};

// 进入第二步
const goToStep2 = () => {
    if (selectedBrands.value.length < 2) {
        ElMessage.warning('请选择至少两个品牌进行合并');
        return;
    }
    currentStep.value = 2;
};

// 返回第一步
const goToStep1 = () => {
    currentStep.value = 1;
    mainBrand.value = null;
};

// 第二步：处理主品牌选择
const handleMainBrandSelection = (selection: any[]) => {
    if (selection.length > 1) {
        ElMessage.warning('只能选择一个品牌作为保留品牌');
        // 当选择多个品牌时，清空mainBrand
        mainBrand.value = null;
        return;
    }
    mainBrand.value = selection.length > 0 ? selection[0] : null;
};

// 确认合并
const handleMerge = () => {
    if (!mainBrand.value) {
        ElMessage.warning('请选择要保留的品牌');
        return;
    }

    // 防止重复点击
    if (merging.value) {
        return;
    }

    const mergeBrands = selectedBrands.value.filter(brand => brand.id !== mainBrand.value.id);

    const mergeInfo = `保留品牌：${mainBrand.value.brandName} (${mainBrand.value.brandCode})\n` +
                     `合并品牌：${mergeBrands.map(b => `${b.brandName} (${b.brandCode})`).join(', ')}\n\n` +
                     `合并后，被合并的品牌将被删除，其相关数据将转移到保留品牌下。此操作不可逆，请确认是否继续？`;

    ElMessageBox.confirm(
        mergeInfo,
        '确认品牌合并',
        {
            confirmButtonText: '确认合并',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: false
        }
    ).then(() => {
        // 设置合并状态为进行中
        merging.value = true;

        // 准备合并数据
        const mergeData = {
            id: mainBrand.value.id,
            ids: mergeBrands.map(b => b.id)
        };

        // 调用合并接口
        return baseService.post("/base/basebrand/merge", mergeData).then((res) => {
            if (res.code == 0) {
                ElMessage.success("品牌合并成功");
                visible.value = false;
                // 刷新父组件数据
                emit("refreshDataList");
            } else {
                ElMessage.error(res.msg || "合并失败");
                // 接口返回错误时，抛出异常以避免显示取消提示
                throw new Error(res.msg || "合并失败");
            }
        }).catch((error) => {
            // 只有在接口调用失败且没有具体错误消息时才显示取消提示
            if (!error.message || error.message === "合并失败") {
                ElMessage.info('已取消合并');
            }
        }).finally(() => {
            // 无论成功或失败都重置合并状态
            merging.value = false;
        });
    }).catch(() => {
        ElMessage.info('已取消合并');
    });
};

const state = reactive({ ...useView(view), ...toRefs(view) });
// 页面进入执行
defineExpose({
    init
});

</script>

<style lang="scss" scoped>
.el-input {
    width: 217px;
}

.el-select {
    width: 217px;
}

// 步骤标题样式
.step-title {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 8px;
}

.step-subtitle {
    font-size: 14px;
    color: #606266;
    margin-bottom: 20px;
}

// 对话框底部按钮样式
.dialog-footer {
    text-align: right;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

::v-deep .el-table .cell {
    white-space: nowrap;
    font-size: 13px;
    height: 18px;
    line-height: 18px;
}

// 表格样式优化
::v-deep .el-table {
    .el-table__header-wrapper {
        th {
            background-color: #f5f7fa;
            color: #909399;
            font-weight: 500;
        }
    }

    .el-table__body-wrapper {
        .el-table__row {
            &:hover {
                background-color: #f5f7fa;
            }
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .el-input {
        width: 100%;
    }

    .step-title {
        font-size: 16px;
    }

    .step-subtitle {
        font-size: 12px;
    }
}
</style>
